package seqlist.stack_queue.queue.impl;

import seqlist.stack_queue.queue.MyQueue;

import java.util.NoSuchElementException;

/**
 * @author yuisama
 * @date 2023/03/22 19:18
 * 普通的链式队列的实现
 **/
public class LinkedQueue<E> implements MyQueue<E> {
    // 队首元素
    private Node head;
    // 队尾元素
    private Node tail;
    // 当前队列的有效元素个数
    private int size;
    private class Node{
        E val;
        Node next;
        Node(E val) {
            this.val = val;
        }
    }



    @Override
    public void offer(E val) {
        Node node = new Node(val);
        if (head == null) {
            // 队列为空时
            head = tail = node;
        }
        tail.next = node;
        tail = node;
        size ++;
    }

    @Override
    public E poll() {
        if (size == 0) {
            throw new NoSuchElementException("queue is empty!cannot poll");
        }
        E val = head.val;
        head = head.next;
        size --;
        return val;
    }

    @Override
    public E peek() {
        if (size == 0) {
            throw new NoSuchElementException("queue is empty!cannot peek");
        }
        return head.val;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("front [");
        for (Node x = head;x != null;x = x.next) {
            sb.append(x.val);
            if (x.next != null) {
                sb.append(", ");
            }
        }
        sb.append("] tail");
        return sb.toString();
    }
}